package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.common.R;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RequestMapping("user")
@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     *用户发短信
     */
    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);
        log.info("code={}",code);
        //session.setAttribute("code",code);
        redisTemplate.opsForValue().set(phone,code,120, TimeUnit.SECONDS);
        return R.success("手机验证码短信发送成功");
    }

    /**
     *用户登录
     */
    @PostMapping("login")
    public R<User> login(@RequestBody Map<String,String> map,HttpSession session){
        //获取用户输入类容
        String phone = map.get("phone");
        String code1 = map.get("code");
        //获取session中的code
        //String code2 = (String) session.getAttribute("code");
        String code2 = (String) redisTemplate.opsForValue().get(phone);
        //判断code是否正确
        if(!StringUtils.equals(code1,code2)){
            return R.error("输入的验证码错误");
        }
        //判断当前用户是否为新用户
        QueryWrapper<User> queryWrap = new QueryWrapper<>();
        queryWrap.eq("phone",phone);
        User user = userService.getOne(queryWrap);
        if(user==null){
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        session.setAttribute("user",user.getId());
        redisTemplate.delete(phone);
        return R.success(user);
    }

}
